/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package me.zhengjie.service.impl;

import lombok.RequiredArgsConstructor;
import me.zhengjie.domain.KwExamRoom;
import me.zhengjie.domain.KwExamStudent;
import me.zhengjie.domain.KwExamTeacher;
import me.zhengjie.domain.KwRoom;
import me.zhengjie.exception.ParameterException;
import me.zhengjie.repository.KwExamRoomRepository;
import me.zhengjie.repository.KwExamStudentRepository;
import me.zhengjie.repository.KwExamTeacherRepository;
import me.zhengjie.repository.KwRoomRepository;
import me.zhengjie.service.KwRoomService;
import me.zhengjie.service.dto.KwRoomDto;
import me.zhengjie.service.dto.KwRoomQueryCriteria;
import me.zhengjie.service.mapstruct.KwRoomMapper;
import me.zhengjie.utils.FileUtil;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;
import me.zhengjie.utils.ValidationUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @author LongYang
 * @website https://el-admin.vip
 * @description 服务实现
 * @date 2021-06-28
 **/
@Service
@RequiredArgsConstructor
public class KwRoomServiceImpl implements KwRoomService {

    private final KwRoomRepository kwRoomRepository;
    private final KwRoomMapper kwRoomMapper;
    private final KwExamRoomRepository kwExamRoomRepository;
    private final KwExamStudentRepository kwExamStudentRepository;
    private final KwExamTeacherRepository kwExamTeacherRepository;


    @Override
    public Map<String, Object> queryAll(KwRoomQueryCriteria criteria, Pageable pageable) {
        Page<KwRoom> page = kwRoomRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        return PageUtil.toPage(page.map(kwRoomMapper::toDto));
    }

    @Override
    public List<KwRoomDto> queryAll(KwRoomQueryCriteria criteria) {
        return kwRoomMapper.toDto(kwRoomRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }

    @Override
    @Transactional
    public KwRoomDto findById(Integer id) {
        KwRoom kwRoom = kwRoomRepository.findById(id).orElseGet(KwRoom::new);
        ValidationUtil.isNull(kwRoom.getId(), "KwRoom", "id", id);
        return kwRoomMapper.toDto(kwRoom);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public KwRoomDto create(KwRoom resources) {
        return kwRoomMapper.toDto(kwRoomRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(KwRoom resources) {
        KwRoom kwRoom = kwRoomRepository.findById(resources.getId()).orElseGet(KwRoom::new);
        ValidationUtil.isNull(kwRoom.getId(), "KwRoom", "id", resources.getId());
        kwRoom.copy(resources);
        kwRoomRepository.save(kwRoom);
        /*修改教室信息后，要同步修改考场中的该教室的信息*/
        List<KwExamRoom> list = kwExamRoomRepository.findByRoomId(resources.getId());
        if (!list.isEmpty()) {
            for (KwExamRoom kwExamRoom : list) {
                kwExamRoom.setRoomName(resources.getNameCn());
                kwExamRoom.setAddress(resources.getAddress());
                kwExamRoom.setSeatNumber(resources.getSeatNumber());
                kwExamRoomRepository.save(kwExamRoom);
            }
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteAll(Integer[] ids) {
        for (Integer id : ids) {
            List<KwExamRoom> examRoomList = kwExamRoomRepository.findByRoomId(id);
            if(!examRoomList.isEmpty()){
                throw new ParameterException("考场信息存在该教室关联信息不允许删除");
            }
            List<KwExamStudent> kwExamStudentList = kwExamStudentRepository.findByRoomId(id);
            if(!kwExamStudentList.isEmpty()){
                throw new ParameterException("考生考试信息存在该教室关联信息不允许删除");
            }
            List<KwExamTeacher> kwExamTeacherList = kwExamTeacherRepository.findByRoomId(id);
            if(!kwExamTeacherList.isEmpty()){
                throw new ParameterException("教师监考信息存在该教室关联信息不允许删除");
            }
            kwRoomRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<KwRoomDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (KwRoomDto kwRoom : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("名称", kwRoom.getNameCn());
            map.put("地点", kwRoom.getAddress());
            map.put("座位数量", kwRoom.getSeatNumber());
            map.put("删除标识（0：未删除，1：已删除）", kwRoom.getDelFlag());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

}